package org.fastsyncer.rest.common;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.ThirdpartyConstant;
import org.fastsyncer.common.entity.MappingTask;
import org.fastsyncer.common.util.ApplicationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 处理第三方应用系统业务
 * 
 * @ClassName: ThridpartAppHandler
 * @Description: 处理第三方应用系统业务
 * @author AE86
 * @date: 2017年9月6日 下午1:53:10
 */
public class ThridpartAppHandler {

	private static final Logger logger = LoggerFactory.getLogger(ThridpartAppHandler.class);

	/**
	 * 检查第三方应用业务系统会话appid
	 * 
	 * @Title: handle
	 * @Description: 检查第三方应用业务系统会话appid
	 * @param request
	 * @return: void
	 */
	public static void checkSessionAppid(HttpServletRequest request) {
		// 检查是否开启第三方应用系统集成
		if (!isEnableAppId()) {
			return;
		}
		
		// 获取第三方应用系统集成appid
		String appIdKey = ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_APP_APPID);
        String appNameKey = ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_APP_APPNAME);
		HttpSession session = request.getSession();
		String appId = (String) session.getAttribute(appIdKey);
		String appName = (String) session.getAttribute(appNameKey);
		if (StringUtils.isBlank(appId)) {
			logger.error("Third-party application system integration appid is empty!");
		}
        if (StringUtils.isBlank(appName)) {
            logger.error("Third-party application system integration appName is empty!");
        }

	}

	/**
	 * 过滤出第三方应用业务系统appid对应的驱动
	 * 
	 * @Title: filter
	 * @Description: 过滤出第三方应用业务系统appid对应的驱动
	 * @param request
	 * @param driverAll
	 *            所有驱动
	 * @return: List<Object>
	 */
	public static List<MappingTask> filter(HttpServletRequest request, List<MappingTask> driverAll, String appId) {
		// 检查是否开启第三方应用系统集成
		if (!isEnableAppId()) {
			return driverAll;
		}

		// 获取第三方应用系统集成appid
		String appIdKey = ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_APP_APPID);
		appId = StringUtils.isBlank(appId) ? (String) request.getSession().getAttribute(appIdKey) : appId;
		if (StringUtils.isBlank(appId) || StringUtils.equals("all", appId)) {
			return driverAll;
		}

		// 要查询的应用系统
		List<MappingTask> list = new ArrayList<MappingTask>();
		for (MappingTask task : driverAll) {
			// 如果是要过滤的驱动就放入返回集合中
			if (appId.equals(task.getAppId())) {
				list.add(task);
			}
		}
		return list;
	}

	/**
	 * 检查是否开启第三方应用系统集成
	 * @Title: isEnableAppId 
	 * @Description: 检查是否开启第三方应用系统集成
	 * @return: boolean 开启：true,未开启：false
	 */
	private static boolean isEnableAppId(){
		String appEnable = ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_APP_ENABLE);
		if (StringUtils.isBlank(appEnable) || !StringUtils.equalsIgnoreCase("true", appEnable)) {
			return false;
		}
		return true;
	}
	
}
